package com.example.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Files;
import com.example.springboot.mapper.FileMapper;
import com.example.springboot.utils.AliOssUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileMapper fileMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        // 生成唯一文件名
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;

        // 上传到OSS
        String filePath = aliOssUtil.upload(file.getBytes(), fileUUID);

        // 存储数据库
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size / 1024);
        saveFile.setUrl(filePath);
        saveFile.setMd5(SecureUtil.md5(file.getInputStream()));
        fileMapper.insert(saveFile);

        return filePath;
    }

    /**
     * 文件下载接口
     */
    @GetMapping("/{fileKey}")
    public void download(@PathVariable String fileKey, HttpServletResponse response) {
        try (InputStream inputStream = aliOssUtil.download(fileKey);
             ServletOutputStream outputStream = response.getOutputStream()) {

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename*=UTF-8''" + URLEncoder.encode(fileKey, "UTF-8"));

            // 流拷贝
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();

        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("文件下载失败");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    /**
     * 删除文件接口
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        Files file = fileMapper.selectById(id);
        if (file != null) {
            // 从OSS删除文件
            String fileKey = extractFileKeyFromUrl(file.getUrl());
            aliOssUtil.delete(fileKey);

            // 标记数据库记录为已删除
            file.setIsDelete(true);
            fileMapper.updateById(file);
        }
        return Result.success();
    }

    /**
     * 批量删除文件接口
     */
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<Files> files = fileMapper.selectList(queryWrapper);

        for (Files file : files) {
            // 从OSS删除文件
            String fileKey = extractFileKeyFromUrl(file.getUrl());
            aliOssUtil.delete(fileKey);

            // 标记数据库记录为已删除
            file.setIsDelete(true);
            fileMapper.updateById(file);
        }
        return Result.success();
    }

    /**
     * 图片上传接口（专为富文本编辑器等场景设计）
     */
    @PostMapping("/uploadImg")
    public Map<String, Object> uploadImg(@RequestParam MultipartFile file) throws IOException {
        String url = upload(file); // 复用上传逻辑

        Map<String, Object> result = new HashMap<>();
        result.put("errno", 0);
        result.put("data", JSONUtil.parseArray("[{\"url\": \"" + url + "\"}]"));
        return result;
    }

    // 其他方法保持不变...

    /**
     * 从URL中提取文件key
     */
    private String extractFileKeyFromUrl(String url) {
        // 根据实际URL格式提取文件key
        // 例如: https://bucket-name.oss-cn-hangzhou.aliyuncs.com/abc123.jpg → abc123.jpg
        return url.substring(url.lastIndexOf("/") + 1);
    }
}